package edu.bath.sensorvisualiser;

import org.jivesoftware.smack.XMPPException;

import android.view.View;

import edu.bath.sensorframework.DataReading;
import edu.bath.sensorframework.Visualisation;
import edu.bath.sensorframework.DataReading.Value;
import edu.bath.sensorframework.client.ReadingHandler;
import edu.bath.sensorframework.client.SensorClient;

public class WorkerThread implements Runnable {
	Visualisation<Float> rt;
	View v;
	public WorkerThread(Visualisation<Float> rt, View v) {
		this.rt = rt;
		this.v = v;
	}
	
	SensorClient sensorClient;
	
	float temp = 0.0f;
	
	public void run() {
		while(sensorClient == null) {
			try {
				sensorClient = new SensorClient("138.38.140.153", "laptop", "pwrvisualiser", "bobbo", "pwrvisualiser@laptop");
			} catch (XMPPException e1) {
				System.out.println("Exception in establishing client.");
				e1.printStackTrace();
			}
		}
		
		sensorClient.addHandler("powerSensor", new ReadingHandler() {
			@Override
			public void handleIncomingReading(String rdf) {
				try {
				DataReading dr = DataReading.fromRDF(rdf);
				System.out.println("Converted it to a DataReading.");
				Value val = dr.findFirstValue(null, "http://bath.edu/sensors/types#celsius", null);
				if(val != null) {
					temp = (Float)val.object;
					System.out.println("Temperature is... "+temp);
				}
				
				rt.addData(temp);
				rt.draw();
				v.postInvalidate();
				}catch(Exception e) {}
			}
		});
		
		try {
			sensorClient.subscribe("powerSensor");
		} catch (XMPPException e1) {
			System.out.println("Exception while subscribing to sensor.");
			e1.printStackTrace();
		}
		
		boolean alive = true;
		while(alive) {
			try {
				if(sensorClient.checkReconnect())
					sensorClient.subscribe("powerSensor");
			} catch (XMPPException e1) {
				System.out.println("Couldn't reconnect.");
				e1.printStackTrace();
				try {
					Thread.sleep(30*1000);
				} catch (InterruptedException e) {}
				continue;
			}
			
//			List<String> pendingData = sensorClient.getPendingData("powerSensor");
//			// Gather data from messages
//			if(pendingData.size() != 0) {
//				System.out.println("Got some data.");
//				for(String data : pendingData) {
//					try {
//						DataReading dr = DataReading.fromRDF(data);
//						System.out.println("Converted it to a DataReading.");
//						Value val = dr.findFirstValue(null, "http://bath.edu/sensors/types#celsius", null);
//						if(val != null) {
//							temp = (Float)val.object;
//							System.out.println("Temperature is... "+temp);
//						}
//					} catch (Exception e) { }
//				}
//				rt.drawTemperature(temp);
//				v.postInvalidate();
//			}
        	
        	// Wait for 60s until more data can have come in
        	try {
				Thread.sleep(30*1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
        }
	}
}
